<template>
  <div class="site-wrapper" :class="{ 'site-sidebar--fold': sidebarFold }" v-loading.fullscreen.lock="loading"
    element-loading-text="拼命加载中">
    <template v-if="!loading">
      <main-navbar />
      <main-sidebar />
      <div class="site-content__wrapper" :style="{ 'min-height': documentClientHeight + 'px' }">
        <main-content v-if="!$store.state.common.contentIsNeedRefresh" />
      </div>
      <audio id="audioneworder" src="src/assets/media/5c88b75889c744149.mp3"></audio>
    </template>
  </div>
</template>

<script>
  import Vue from 'vue'
  import MainNavbar from './main-navbar'
  import MainSidebar from './main-sidebar'
  import MainContent from './main-content'
  import SockJS from "sockjs-client";
  import Stomp from "stompjs";
  import {
    getToken
  } from "@/utils/index";
  Vue.prototype.playAudio = () => {
    let buttonAudio = document.getElementById('audioneworder');
    buttonAudio.play()
  }
  export default {
    provide() {
      return {
        // 刷新
        refresh() {
          this.$store.commit('common/updateContentIsNeedRefresh', true)
          this.$nextTick(() => {
            this.$store.commit('common/updateContentIsNeedRefresh', false)
          })
        }
      }
    },
    data() {
      return {
        loading: true,
        stompClient: "",
        timer: "",
        baseUrl: ""
      }
    },
    components: {
      MainNavbar,
      MainSidebar,
      MainContent
    },
    computed: {
      documentClientHeight: {
        get() {
          return this.$store.state.common.documentClientHeight
        },
        set(val) {
          this.$store.commit('common/updateDocumentClientHeight', val)
        }
      },
      sidebarFold: {
        get() {
          return this.$store.state.common.sidebarFold
        }
      },
      userId: {
        get() {
          return this.$store.state.user.id
        },
        set(val) {
          this.$store.commit('user/updateId', val)
        }
      },
      userName: {
        get() {
          return this.$store.state.user.name
        },
        set(val) {
          this.$store.commit('user/updateName', val)
        }
      }
    },
    created() {
      this.getUserInfo()
    },
    mounted() {
      this.resetDocumentClientHeight()
      this.initWebSocket();
    },
    beforeDestroy: function () {
      this.disconnect();
      clearInterval(this.timer);
    },
    methods: {
      // 重置窗口可视高度
      resetDocumentClientHeight() {
        this.documentClientHeight = document.documentElement['clientHeight']
        window.onresize = () => {
          this.documentClientHeight = document.documentElement['clientHeight']
        }
      },
      // 获取当前管理员信息
      getUserInfo() {
        this.$http({
          url: this.$http.adornUrl('/sys/user/info'),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            this.loading = false
            this.userId = data.user.userId
            this.userName = data.user.username
          }
        })
      },
      //webSocket的接入
      initWebSocket() {
        this.connection();
        let that = this;
        // 断开重连机制,尝试发送消息,捕获异常发生时重连
        this.timer = setInterval(() => {
          try {
            that.stompClient.send("webSocket心跳检测");
          } catch (err) {
            console.log("断线了: " + err);
            that.connection();
          }
        }, 5000);
      },
      connection() {
        var that = this

        if (process.env.NODE_ENV === "development") {
          this.baseUrl = "http://127.0.0.1:8082/engineering";
        }
        if (process.env.NODE_ENV === "production") {
          this.baseUrl = window.SITE_CONFIG['baseUrl'];
        }
        console.log(this.baseUrl)
        // 建立连接对象
        var socket = new SockJS(
          this.baseUrl + "/websocket?token=" + getToken()
        );
        // 获取STOMP子协议的客户端对象
        this.stompClient = Stomp.over(socket);
        // 向服务器发起websocket连接{
        this.stompClient.connect({}, () => {
            //订阅广播消息
            this.stompClient.subscribe("/topic/notice", function (response) {
              console.log('dingyueguangbo');
              var res = JSON.parse(response.body);
              that.$notify({
                title: res.title,
                dangerouslyUseHTMLString: true,
                message: '<div>用户：<strong>' + res.fromUserName + '</strong></div><div><i>' + res.content +
                  '</i></div>',
                duration: 4500
              });
            });
            //订阅新订单消息
            this.stompClient.subscribe('/user/queue/msg/new', function (response) {
              var res = JSON.parse(response.body);
              that.$notify({
                title: res.title,
                dangerouslyUseHTMLString: true,
                message: '<div>用户：<strong>' + res.fromUserName + '</strong></div><div><i>' + res.content +
                  '</i></div>',
                duration: 4500
              });
              Vue.prototype.playAudio()
              that.bus.$emit('refreshTodoList')
            });
            //订阅刷新订单列表消息
            this.stompClient.subscribe('/user/queue/todo/refresh', function (response) {
              console.log("接收到了")
              Vue.prototype.playAudio()
              that.bus.$emit('refreshTodoList')
            });
            //订阅实时数据信息
            this.stompClient.subscribe('/user/queue/realtime/data', function (response) {
              console.log("实时数据信息")
              Vue.prototype.playAudio()
              var res = JSON.parse(response.body);
              that.bus.$emit('refreshTodoList', res)
            });
          },
          err => {
            // 连接发生错误时的处理函数
            console.log("失败");
            console.log(err);
            // that.connection();
          }
        );
      },
      // 断开连接
      disconnect() {
        if (this.stompClient) {
          this.stompClient.disconnect();
        }
      }
    }
  }

</script>
